package com.vnp.cooking;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ApplicationErrorReport.CrashInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.viewpagerindicator.PageIndicator;
import com.vnp.cooking.UIcontrols.MyViewPager;
import com.vnp.cooking.adapter.TabsAdapter;
import com.vnp.cooking.fragmenthome.FragListCoopad;
import com.vnp.cooking.fragmenthome.FragNhabep;
import com.vnp.cooking.fragmenthome.FrgCreateCooking;
import com.vnp.cooking.fragmenthome.FrgCreateCooking1;
import com.vnp.cooking.fragmenthome.FrgGianbepcuatoi;
import com.vnp.cooking.fragmenthome.FrgGianbepcuatoi1;
import com.vnp.cooking.fragmenthome.FrgLoaimon;
import com.vnp.cooking.fragmenthome.FrgBosuutap;
import com.vnp.cooking.fragmenthome.FrgTaomonan;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.Common;
import com.vnp.cooking.utils.KeyboardHelper;
import com.vnp.cooking.utils.PreferenceHelper;

public class MainActivity extends SherlockFragmentActivity implements OnClickListener, OnEditorActionListener{
	
	private Fragment mContent;
	FrameLayout frm;
	RelativeLayout actionbar;
	EditText searchBar;
	
	// Khai bao button actionbar
	ImageButton btnOpenMenu, btnSearch;
	
	ViewGroup vg;
	FragmentPagerAdapter adapter;
	PageIndicator indicator ;
	MyViewPager mViewPager;
	
	// khai bao tabhost
	private TabHost mTabHost;
	private TabsAdapter mTabsAdapter;
	
	Boolean backAgain = false;
	int mCurrentPosition;
	Handler mHandler = new Handler();

	PreferenceHelper preferenceHelper;
	/*public MainActivity() {
		super(R.string.app_name);
	}*/

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.content_frame);
		
		preferenceHelper = new PreferenceHelper(this);
		
		/*if (savedInstanceState != null) {
			mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
		}
		
		if (mContent == null) {
			mContent = new MainView();
		}
		
		setContentView(R.layout.content_frame);
		getSupportFragmentManager()
		.beginTransaction()
		.replace(R.id.content_frame, mContent).commit();*/
		
		
//		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
//		setSlidingActionBarEnabled(true);
		// khai bao layout 
		frm = (FrameLayout) findViewById(R.id.frm);
		actionbar = (RelativeLayout) findViewById(R.id.actionbar);
		searchBar = (EditText) findViewById(R.id.searchBar);
		
		btnOpenMenu = (ImageButton)findViewById (R.id.btnOpenMenu);
		btnSearch = (ImageButton) findViewById(R.id.btnSearch);
		searchBar.setOnEditorActionListener(this);
		
		btnOpenMenu.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		
		// khoi tao tabhost
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);

	    mTabHost.setup();



	    mViewPager = (MyViewPager)findViewById(R.id.pager);
	    // tao intent chuyen sang activity moi

	    
	    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
	    
	    // demo cai custom tab image
	    mTabsAdapter.addTab(mTabHost.newTabSpec("1").setIndicator("", getResources().getDrawable(R.drawable.img_tab_home_selector)), FragNhabep.class, null);
	    mTabsAdapter.addTab(mTabHost.newTabSpec("2").setIndicator("", getResources().getDrawable(R.drawable.img_tab_loaimon_selector)), FrgLoaimon.class, null);
	    mTabsAdapter.addTab(mTabHost.newTabSpec("3").setIndicator("", getResources().getDrawable(R.drawable.img_tab_taomonan_selector)), FrgCreateCooking.class, null );
//	    mTabsAdapter.addTab(mTabHost.newTabSpec("3").setIndicator("", getResources().getDrawable(R.drawable.img_tab_taomonan_selector)).setContent(new Intent(MainActivity.this, FrgCreateCooking1.class)), null, null);
	    mTabsAdapter.addTab(mTabHost.newTabSpec("4").setIndicator("", getResources().getDrawable(R.drawable.img_tab_thongbao_selector)), FrgBosuutap.class, null);
	    mTabsAdapter.addTab(mTabHost.newTabSpec("5").setIndicator("", getResources().getDrawable(R.drawable.img_tab_canhan_selector)), FrgGianbepcuatoi1.class, null);

	    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
	            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
	    params.weight = 0.7f;
	    params.gravity = Gravity.CENTER;
	    
	     for (int i = 0; i < 5; i++) {
	    	mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = R.dimen.heigth_tabhost;
	    	mTabHost.getTabWidget().getChildAt(i).setPadding(0,0,0,0);
	    }
	     
	    
	    if (savedInstanceState != null) {

	        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));

	    }
	    
	    
	    mTabHost.getTabWidget().setStripEnabled(false);
	    mViewPager.setPagingEnabled(false);
	    mCurrentPosition = mTabHost.getCurrentTab();
	    
	    updateDeviceId();
		
	    
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnOpenMenu:
//			toggle();
			break;

		case R.id.btnSearch:
			actionbar.setVisibility(View.GONE);
			frm.setVisibility(View.VISIBLE);
			KeyboardHelper.displaySoftKeyboard(MainActivity.this, searchBar);
			break;
		}
		
	}

	@Override
	public void onBackPressed() {
		if (mCurrentPosition == 0) {
			if(backAgain==false) {
				backAgain = true;
//				Toast.makeText(this, "Nhấn lại lần nữa để thoát", 2000).show();
				mHandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						backAgain = false;
					}
				}, 2000);
			} else {
				backAgain = false;
				finish();
			}
		} else if (mCurrentPosition == 1) {
		} else if (mCurrentPosition == 2) {
		}
		
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
	}
	
	void updateDeviceId() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				super.onSuccess(re);
				try {
					int status = re.getInt("status");
					if (status == 200) {
						Log.i("DATA", "CAP NHAT THANH CONG ANUONG_DEVICE_ID : "+preferenceHelper.getAnuongDeviceId());
					} else if (status == 400) {
						
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		
		httpClientHelper.updateDevice(preferenceHelper.getID(), Common.MOBILE_TYPE, preferenceHelper.getAnuongDeviceId());
	}
	
	// show notification
	public MessageReceiver messageReceiver = new MessageReceiver();
	public class MessageReceiver extends  BroadcastReceiver  {

		@Override
		public void onReceive(final Context context, Intent intent) {
			Bundle extra = intent.getExtras();
			if (extra != null) {
				String action = intent.getAction();
				if (action.equals(Common.DISPLAY_MESSAGE_ACTION)) {
					
				} 
			}
		}

	}
	@Override
	protected void onResume() {
		super.onResume();
		IntentFilter i = new IntentFilter();
		i.addAction(Common.DISPLAY_MESSAGE_ACTION);
		registerReceiver(messageReceiver, i);
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(messageReceiver);
	}

	
	
	
	
	
	
	
}
